package _1_5_type_convert;

import _1_2_ClassAndObject.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by bpzj on 9/29/2018.
 */
public class JavaBeanToMap {

    @Test
    public void useReflect() {
        User bean = new User();
        bean.setAge(1);
        bean.setHeight(3);
        bean.setName("ym");

        Map<String, Object> map = new HashMap<>();
        // 这里用 getDeclaredMethods() 获取 methods 之后，判断 methods 中的 get 方法
        // 也可以用 getDeclaredFields() 获取 Field[] 之后，判断 Field[]
        /**  {@link _5_reflect.util.ArgsCheck#checkAllFieldNotEmpty(Object)}  */
        try {
            Class<? extends Object> c = bean.getClass();
            Method[] methods = c.getDeclaredMethods();
            for (Method method : methods) {
                String methodName = method.getName();
                if (methodName.indexOf("get") == 0) {
                    String key = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
                    map.put(key, method.invoke(bean));
                }
            }
        } catch (Throwable e) {
            //log error
        }

        System.out.println(map);
    }

    @Test
    public void useJackson() {
        User bean = new User();
        bean.setAge(1);
        bean.setHeight(3);
        bean.setName("ym");

        ObjectMapper m = new ObjectMapper();
        Map<String, Object> maps = m.convertValue(bean, Map.class);
        System.out.println(maps);
    }

    @Test
    public void useGoogleGson() {
    }
}
